package gov.kqqzyyy.monkey.orderpad.network.base;

import android.accounts.NetworkErrorException;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;


import gov.kqqzyyy.monkey.orderpad.network.bean.BaseResponse;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {

    private Disposable mDisposable;

    protected BaseObserver() {

    }

    @Override
    public void onSubscribe(Disposable d) {
        onRequestStart();
        mDisposable = d;
    }

    @Override
    public void onNext(BaseResponse<T> tBaseResponse) {
        onRequestEnd();
        if (tBaseResponse.getCode().equals("2000")) {
            try {
                onSuccees(tBaseResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                onCodeError(tBaseResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        onRequestEnd();
        try {
            onFailure(e, e instanceof ConnectException
                    || e instanceof TimeoutException
                    || e instanceof NetworkErrorException
                    || e instanceof UnknownHostException);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onComplete() {
    }

    /**
     * 返回成功
     */
    protected abstract void onSuccees(BaseResponse<T> t) throws Exception;

    /**
     * 返回成功了,但是code错误
     */
    protected void onCodeError(BaseResponse<T> t) {
    }

    /**
     * 返回失败
     *
     * @param e              异常参数
     * @param isNetWorkError 是否是网络错误
     * @throws Exception 异常
     */
    protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;

    private void onRequestStart() {
    }

    private void onRequestEnd() {

    }

    //停止请求
    public void doCancelRequest() {
        mDisposable.dispose();
    }


}
